#include <iostream>
#include "InetAddr.hpp"
#include "basic_socket.hpp"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>
static const int gbacklog = 16;
class TCPServer : public basic_socket
{
    virtual void CreateSocket() override
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock == -1)
        {
            std::cerr << "Create Socket Error!" << std::endl;
            exit(SOCKET_ERROR);
        }
    }
    virtual void BindSocket() override
    {
        sockaddr_in local;
        memset(&local, 0, sizeof(local));
        inet_pton(AF_INET, _addr.IP().c_str(), &local.sin_addr.s_addr);
        local.sin_family = AF_INET;
        local.sin_port = htons(_addr.Port());
        int n = bind(_listensock, reinterpret_cast<const sockaddr *>(&local), sizeof(local));
        if (n == -1)
        {
            std::cerr << "Listensock Bind Error!" << std::endl;
            exit(BIND_ERROR);
        }
    }
    virtual void SetListenSocket()
    {
        int n = listen(_listensock, gbacklog);
        if (n == -1)
        {
            std::cerr << "Set Listensock Error!" << std::endl;
            exit(SETSOCK_ERROR);
        }
    }

public:
    TCPServer(uint16_t port, std::string ip_addr) : _addr(port, ip_addr)
    {
        CreateTCPServer();
    }
    void Start()
    {
        while(true)
        {
            int sockfd = accept(_listensock,nullptr,nullptr);
            if(sockfd == -1)
            {
                std::cerr << "accept error!" <<std::endl;
                continue;
            }
            
        }
    }

protected:
    int _listensock;
    InetAddr _addr;
};